// Dwarf.Unmanaged.MPI.cpp : Defines the entry point for the console application.
//

#include "Dwarf.Unmanaged.Mpi.h"

// The settings for this dwarf.
static Settings* settings;

// Get settings from the command line.
static int getSettings(int argc, char** argv, Solver *solver) 
{
	setvbuf( stdout, NULL, _IONBF, 0 );

	int error = 0;
    if (solver->isRootThread) 
    {
        settings = new Settings();
        if (settings->init(argc,argv,solver)) 
        {            
            delete settings;
            error = 1;
        } 
    }
    //Distribute error if that occurred while parsing.
    MPI_Bcast(&error, 1, MPI_INT, NUMBER_ROOT_PROCESS, MPI_COMM_WORLD);
    if (error == 1 ) return -1;

    /*End of setup*/
    return 0;
}

void main(int argc, char** argv)
{
	// initialize MPI
    MPI_Init(&argc, &argv);

	Solver* solver = new Solver();
    if (getSettings(argc, argv, solver)) 
    {
    	MPI_Finalize();
        delete solver;
        exit(-1);
    }

    MPI_Barrier(MPI_COMM_WORLD);

    if (solver->isRootThread) 
    {
        settings->start();              // Start new time count.
    }

    solver->Solve();                    // Solve the current problem.

    MPI_Barrier(MPI_COMM_WORLD);

    if (solver->isRootThread) 
    {
        settings->finish(solver);       // Stop the time count and write results. 
        delete settings;
    } 
    MPI_Finalize();
    delete solver;
}